package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ContinueInfo;
import com.xmy.cultivate.entity.views.RenewClassRecord;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.RenewClassMapper;
import com.xmy.cultivate.mapper.RenewDataMapper;
import com.xmy.cultivate.mapper.TeacherContinueInfoMapper;
import com.xmy.cultivate.respons.RenewHistoryData;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.IRenewClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ConfigData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 续班表 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-23
 */
@Service
public class RenewClassServiceImpl extends ServiceImpl<RenewClassMapper, RenewClass> implements IRenewClassService {

    @Autowired
    RenewClassMapper renewClassMapper;

    @Autowired
    RenewDataMapper renewDataMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    TeacherContinueInfoMapper teacherContinueInfoMapper;

    /**
     *
     * @param schoolIdList
     * @param SubjectsId
     * @param YearPart
     * @param QuarterNum
     * @param TeacherName
     * @param StartDate
     * @param EndDate
     * @param type 1老师，2校区老师，3校长，4校区
     * @return
     */
    public List<RenewClassRecord> getRenewRecord(String[] schoolIdList,String SubjectsId,Integer YearPart,Integer QuarterNum,String TeacherName,String StartDate,String EndDate,Integer type){

        QueryWrapper queryWrapper = new QueryWrapper();
        if(schoolIdList.length>0){
            queryWrapper.in("school_id",schoolIdList);
        }else{
            //queryWrapper.eq("school_id",0);
        }



        queryWrapper.eq(StringUtils.isNotBlank(SubjectsId),"subjects_id",SubjectsId);
        queryWrapper.eq("year_part",YearPart);
        queryWrapper.eq("quarter_num",QuarterNum);
        queryWrapper.eq("deleted",0);
        //queryWrapper.eq("status",1);

        Map<String,Integer> nextQuarter = ConfigData.getNextQuarter(YearPart,QuarterNum);

        List<RenewClassRecord> renewClassRecordList = null;
        List<String> groupBys;
        //1老师，2校区老师，3校长，4校区
        if(type.equals(1)){
            queryWrapper.like(StringUtils.isNotBlank(TeacherName),"teacher_name",TeacherName);
            //where (`a`.`deleted` = 0) group by `a`.`teacher_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(SubjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);


            renewClassRecordList =  renewClassMapper.getRenewRecordPerson(queryWrapper);
        }else if(type.equals(2)){
            queryWrapper.like(StringUtils.isNotBlank(TeacherName),"teacher_name",TeacherName);
            //group by `a`.`school_id`,`a`.`teacher_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(SubjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList =  renewClassMapper.getRenewRecord(queryWrapper);
        }else if(type.equals(3)){
            queryWrapper.like(StringUtils.isNotBlank(TeacherName),"teacher_name",TeacherName);
            queryWrapper.inSql("teacher_id","select admin_id from role_admin where role_id = 1568160887369994242 ");

            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(SubjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList =  renewClassMapper.getRenewRecordPerson(queryWrapper);
        }else if(type.equals(4)){
            //where (`a`.`deleted` = 0) group by `a`.`school_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            if(StringUtils.isNotBlank(SubjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList =  renewClassMapper.getRenewRecordSchool(queryWrapper);
        }




        for (RenewClassRecord renewClassRecord :renewClassRecordList){

            //@Param("schoolId") Long schoolId,@Param("subjectsId") Long subjectsId,@Param("renewTeacherId") Long renewTeacherId,@Param("yearPart") Integer yearPart,@Param("quarterNum") Integer quarterNum
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

            //1老师，2校区老师，3校长，4校区
            if(type.equals(1)){
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(2)){
                studentGradeQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(3)){
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(4)){
                studentGradeQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            }

            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId),"subjects_id",SubjectsId);
            studentGradeQueryWrapper.eq("year_part",YearPart);
            studentGradeQueryWrapper.eq("quarter_num",QuarterNum);
            studentGradeQueryWrapper.eq("deleted",0);
            studentGradeQueryWrapper.eq("status",1);
            //studentGradeQueryWrapper.ne("status",2);
            //studentGradeQueryWrapper.ne("status",3);
            studentGradeQueryWrapper.ne("reading_status",2);
            //studentGradeQueryWrapper.and(i->i.eq("status",1).or(j->j.ne("status",1).gt("use_course_count",0)));


            //studentGradeQueryWrapper.or(i->i.gt("use_course_count",0).ne("status",1).eq("deleted",0).eq("subjects_id",SubjectsId).eq("year_part",YearPart).eq("quarter_num",QuarterNum));

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);


            //@Param("schoolId") Long schoolId, @Param("teacherId") Long teacherId, @Param("subjectsId") Long subjectsId, @Param("yearPart") Integer yearPart, @Param("quarterNum") Integer quarterNum, @Param("level") Integer level
            //,renewClassRecord.getTeacherId(),SubjectsId,nextQuarter.get("yearPart"),nextQuarter.get("num"),1
            //@Select("select  count(id) as count from renew_data where  level=#{level} and year_class_id <>9 and year_class_id is not null and type=1")

            //应续人数
            //1老师，2校区老师，3校长，4校区
            QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
            if(type.equals(1)){
                renewDataQueryWrapper.eq("teacher_id",renewClassRecord.getTeacherId());
            }else if(type.equals(2)){
                renewDataQueryWrapper.eq("teacher_id",renewClassRecord.getTeacherId());
                renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            }else if(type.equals(3)){
                //renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                renewDataQueryWrapper.eq("teacher_id",renewClassRecord.getTeacherId());
            }else if(type.equals(4)){
                renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                renewDataQueryWrapper.inSql("teacher_id","select teacher_id from grade where school_id="+renewClassRecord.getSchoolId()+"");
            }

            renewDataQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId),"subjects_id",SubjectsId);
            renewDataQueryWrapper.eq("year_part_renew",nextQuarter.get("yearPart"));
            renewDataQueryWrapper.eq("quarter_num_renew",nextQuarter.get("num"));
            renewDataQueryWrapper.eq("level",1);
            renewDataQueryWrapper.isNotNull("year_class_id");
            renewDataQueryWrapper.eq("type",1);


            //renewDataQueryWrapper.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            //春续暑，暑续秋，9年级不算在续班率里
            if(QuarterNum.equals(2)||QuarterNum.equals(3)){
                //小于 <
                renewDataQueryWrapper.lt("year_class_id",9);
            }else {
                //小于等于 <=
                renewDataQueryWrapper.le("year_class_id",9);
            }

            Integer shouldRenewCount = renewDataMapper.getShouldCount(renewDataQueryWrapper);
            renewClassRecord.setShouldRenewCount(shouldRenewCount);


            /**
             * 已续人数
             */

            QueryWrapper<RenewData> renewDataQueryWrapperAlready = new QueryWrapper<>();
            //1老师，2校区老师，3校长，4校区
            if(type.equals(1)){
                renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
            }else if(type.equals(2)){
                renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
                renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
            }else if(type.equals(3)){
                renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
                //renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
            }else if(type.equals(4)){
                renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
            }


            renewDataQueryWrapperAlready.eq(StringUtils.isNotBlank(SubjectsId),"subjects_id",SubjectsId);
            renewDataQueryWrapperAlready.eq("year_part_renew",nextQuarter.get("yearPart"));
            renewDataQueryWrapperAlready.eq("quarter_num_renew",nextQuarter.get("num"));
            renewDataQueryWrapperAlready.eq("level",1);

            renewDataQueryWrapperAlready.isNotNull("year_class_id");
            renewDataQueryWrapperAlready.eq("type",1);
            renewDataQueryWrapperAlready.eq("is_renew",1);
            renewDataQueryWrapperAlready.eq("true_renew",1);
            //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            if(QuarterNum.equals(2)||QuarterNum.equals(3)){
                renewDataQueryWrapperAlready.lt("year_class_id",9);
            }else {
                renewDataQueryWrapperAlready.le("year_class_id",9);
            }

            if(StringUtils.isNotBlank(StartDate)){
                renewDataQueryWrapperAlready.ge("renew_date",StartDate);
            }

            if(StringUtils.isNotBlank(EndDate)){
                renewDataQueryWrapperAlready.le("renew_date",EndDate);
            }


            Integer alreadyRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
            renewClassRecord.setAlreadyRenewCount(alreadyRenewCount);


            /**
             * //当天的续班人数，已续人数
             */
            /*if(StartDate != null && StartDate !=""){
                renewDataQueryWrapperAlready = new QueryWrapper<>();
                //1老师，2校区老师，3校长，4校区
                if(type.equals(1)){
                    renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
                }else if(type.equals(2)){
                    renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
                    renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
                }else if(type.equals(3)){
                    //renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                    renewDataQueryWrapperAlready.eq("teacher_id",renewClassRecord.getTeacherId());
                }else if(type.equals(4)){
                    renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
                }

                renewDataQueryWrapperAlready.eq("subjects_id",renewClassRecord.getSubjectsId());
                renewDataQueryWrapperAlready.eq("year_part_renew",nextQuarter.get("yearPart"));
                renewDataQueryWrapperAlready.eq("quarter_num_renew",nextQuarter.get("num"));
                renewDataQueryWrapperAlready.eq("level",1);

                renewDataQueryWrapperAlready.isNotNull("year_class_id");
                renewDataQueryWrapperAlready.eq("type",1);
                renewDataQueryWrapperAlready.eq("is_renew",1);
                //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
                if(QuarterNum.equals(2)||QuarterNum.equals(3)){
                    renewDataQueryWrapperAlready.lt("year_class_id",9);
                }else {
                    renewDataQueryWrapperAlready.le("year_class_id",9);
                }
                renewDataQueryWrapperAlready.eq("renew_date",StartDate);

                Integer dateRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
                renewClassRecord.setDateRenewCount(dateRenewCount);
            }*/


            //流失率
            /*Integer runOffCount = renewClassMapper.getRunOffCount(renewClassRecord.getSchoolId(),Long.parseLong(SubjectsId),renewClassRecord.getTeacherId(),YearPart,QuarterNum);
            renewClassRecord.setRunOffCount(runOffCount);
            */
            if(shouldRenewCount>0){
                BigDecimal b1 = new BigDecimal(Double.toString(alreadyRenewCount));
                BigDecimal b2 = new BigDecimal(Double.toString(shouldRenewCount));
                BigDecimal b3 = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);

                renewClassRecord.setRenewRate(b3.multiply(new BigDecimal(100)));
            }
            //float renewRate = renewClassRecord.getAlreadyRenewCount()/renewClassRecord.getShouldRenewCount();
        }
        return  renewClassRecordList;
    }

    public List<RenewClassRecord> getRenewRecordForTeacher(Long SubjectsId,Integer YearPart,Integer QuarterNum,String TeacherName,String StartDate,String EndDate){

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.isNotBlank(SubjectsId.toString()),"subjects_id",SubjectsId);
        queryWrapper.eq("year_part",YearPart);
        queryWrapper.eq("quarter_num",QuarterNum);

        Map<String,Integer> nextQuarter = ConfigData.getNextQuarter(YearPart,QuarterNum);


        List<RenewClassRecord> renewClassRecordList =  renewClassMapper.getRenewRecord(queryWrapper);
        for (RenewClassRecord renewClassRecord :renewClassRecordList){

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            studentGradeQueryWrapper.eq("subjects_id",SubjectsId);
            studentGradeQueryWrapper.eq("teacher_id",renewClassRecord.getTeacherId());
            studentGradeQueryWrapper.eq("year_part",YearPart);
            studentGradeQueryWrapper.eq("quarter_num",QuarterNum);
            studentGradeQueryWrapper.eq("deleted",0);
            studentGradeQueryWrapper.ne("status",2);

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);

            //应续人数
            QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
            renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("teacher_id",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("subjects_id",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("year_part_renew",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("quarter_num_renew",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("level",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.ne("year_class_id",9);
            renewDataQueryWrapper.ne("year_class_id",null);
            renewDataQueryWrapper.ne("type",1);

            Integer shouldRenewCount = renewDataMapper.getShouldCount(renewDataQueryWrapper);
            renewClassRecord.setShouldRenewCount(shouldRenewCount);


            /**
             * 已续人数
             */

            QueryWrapper<RenewData> renewDataQueryWrapperAlready = new QueryWrapper<>();
            renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("teacher_id",renewClassRecord.getTeacherId());
            renewDataQueryWrapper.eq("subjects_id",renewClassRecord.getSubjectsId());
            renewDataQueryWrapper.eq("year_part_renew",nextQuarter.get("yearPart"));
            renewDataQueryWrapper.eq("quarter_num_renew",nextQuarter.get("num"));
            renewDataQueryWrapper.eq("level",1);
            renewDataQueryWrapper.ne("year_class_id",9);
            renewDataQueryWrapper.ne("year_class_id",null);
            renewDataQueryWrapper.ne("type",1);
            renewDataQueryWrapperAlready.ne("is_renew",1);



            Integer alreadyRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);

            renewClassRecord.setAlreadyRenewCount(alreadyRenewCount);

            Integer runOffCount = renewClassMapper.getRunOffCount(renewClassRecord.getSchoolId(),SubjectsId,renewClassRecord.getTeacherId(),YearPart,QuarterNum);
            renewClassRecord.setRunOffCount(runOffCount);

            if(shouldRenewCount>0){
                BigDecimal b1 = new BigDecimal(Double.toString(alreadyRenewCount));
                BigDecimal b2 = new BigDecimal(Double.toString(shouldRenewCount));
                BigDecimal b3 = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);

                renewClassRecord.setRenewRate(b3.multiply(new BigDecimal(100)));
            }
            //float renewRate = renewClassRecord.getAlreadyRenewCount()/renewClassRecord.getShouldRenewCount();
        }
        return  renewClassRecordList;
    }

    public List<RenewClassRecord> getPayFee(String subjectsId,Integer type,Integer quarterNum){
        Quarter quarter = iQuarterService.getNowQuarter();

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq("year_part",quarter.getYearPart());
        queryWrapper.eq("quarter_num",quarter.getNum());
        queryWrapper.eq("deleted",0);

        List<RenewClassRecord> renewClassRecordList = null;
        List<String> groupBys;
        //1老师，2校区老师，3校长，4校区
        if(type.equals(1)){
            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(subjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList =  renewClassMapper.getRenewRecordPerson(queryWrapper);
        }else if(type.equals(2)){
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(subjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList =  renewClassMapper.getRenewRecord(queryWrapper);
        }else if(type.equals(3)){
            queryWrapper.inSql("teacher_id","select admin_id from role_admin where role_id = 1568160887369994242 ");
            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if(StringUtils.isNotBlank(subjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList =  renewClassMapper.getRenewRecordPerson(queryWrapper);
        }else if(type.equals(4)){
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            if(StringUtils.isNotBlank(subjectsId)){
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList =  renewClassMapper.getRenewRecordSchool(queryWrapper);
        }

        for (RenewClassRecord renewClassRecord :renewClassRecordList){
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

            //1老师，2校区老师，3校长，4校区
            if(type.equals(1)){
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(2)){
                studentGradeQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(3)){
                studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+renewClassRecord.getTeacherId()+"");
            }else if(type.equals(4)){
                studentGradeQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
            }

            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            studentGradeQueryWrapper.eq("year_part",quarter.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num",quarter.getNum());
            studentGradeQueryWrapper.eq("deleted",0);
            studentGradeQueryWrapper.eq("status",1);
            studentGradeQueryWrapper.ne("reading_status",2);
            //studentGradeQueryWrapper.and(i->i.eq("status",1).or(j->j.ne("status",1).gt("use_course_count",0)));


            //studentGradeQueryWrapper.or(i->i.gt("use_course_count",0).ne("status",1).eq("deleted",0).eq("subjects_id",SubjectsId).eq("year_part",YearPart).eq("quarter_num",QuarterNum));

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);



            //应续人数
            //1老师，2校区老师，3校长，4校区
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("deleted",0);
            orderDetailQueryWrapper.ne("status",2);
            orderDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            List<String> groupBy = new ArrayList<>();
            groupBy.add("student_id");
            StringBuilder where02 = new StringBuilder();
            if(type.equals(1)){
                orderDetailQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part ="+quarter.getYearPart()+" and a.quarter_num ="+quarter.getNum()+" and subjects_id="+subjectsId+" and b.teacher_id = "+renewClassRecord.getTeacherId()+" and a.deleted=0 and a.status =1");
            }else if(type.equals(2)){
                groupBy.add("school_id");
                orderDetailQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part ="+quarter.getYearPart()+" and a.quarter_num ="+quarter.getNum()+" and subjects_id="+subjectsId+" and a.school_id="+renewClassRecord.getSchoolId()+" and b.teacher_id = "+renewClassRecord.getTeacherId()+" and a.deleted=0 and a.status =1");
            }else if(type.equals(3)){
                orderDetailQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part ="+quarter.getYearPart()+" and a.quarter_num ="+quarter.getNum()+" and subjects_id="+subjectsId+" and b.teacher_id = "+renewClassRecord.getTeacherId()+" and a.deleted=0 and a.status =1");
            }else if(type.equals(4)){
                groupBy.add("school_id");
                orderDetailQueryWrapper.inSql("student_id","select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part ="+quarter.getYearPart()+" and a.quarter_num ="+quarter.getNum()+" and subjects_id="+subjectsId+" and a.school_id="+renewClassRecord.getSchoolId()+" and a.deleted=0 and a.status =1");

            }
            orderDetailQueryWrapper.groupBy(groupBy);

            where02.append(" and residue_course_count >= 45");
            Integer bigFifteen = orderDetailMapper.getCourseCount(orderDetailQueryWrapper,where02.toString());

            where02 = new StringBuilder();
            where02.append(" and residue_course_count < 45");
            Integer littleFifteen = orderDetailMapper.getCourseCount(orderDetailQueryWrapper,where02.toString());

            renewClassRecord.setBigFifteen(bigFifteen);
            renewClassRecord.setLittleFifteen(littleFifteen);
        }
        return  renewClassRecordList;
    }

    public Integer getCourseNumForPeriods(Integer num){
        Integer[] courseNum = new Integer[]{0,45,90,135,180,225,270};
        Integer name = 45;
        if(num>=0 && num<courseNum.length){
            name = courseNum[num];
        }
        return name;
    }



    @Override
    public List<RenewClassRecord> getPayFeeHb(String schoolId, Integer yearPart, Integer quarterNum, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer lessonType, String yearClassId, String classTypeId, Integer periodsNum, String name) throws ParseException {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);

        if (yearPart == null){
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null){
            quarterNum = quarterNow.getNum();
        }
        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart,quarterNum,endDate,quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory =  renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标
        boolean dateHistory = renewHistoryData.isDateHistory();//按天看的历史数据


        Integer payYearPart = yearPart;
        Integer payQuarterNum = quarterNum;

        Integer searchYearAndQuarter = Integer.parseInt(yearPart+""+quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && targetType.equals(1)){
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart,quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的下个学期后的学期
            if (nextQuater!=null){
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart()+""+nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        List<RenewClassRecord> renewClassRecordList = new ArrayList<>();
        if(!dateHistory){
            renewClassRecordList = orderDetailMapper.getPayFee(schoolId,yearPart,quarterNum,subjectsId,type,startDate,endDate,trackId,isHistory,lessonType,searchYearAndQuarter,nextYearAndQuarter,payYearPart,payQuarterNum,yearClassId,classTypeId,feeCourseNum,periodsNum,name);
        }else {
            renewClassRecordList = orderDetailMapper.getPayFeeByHistory(schoolId,yearPart,quarterNum,subjectsId,type,startDate,endDate,trackId,lessonType,yearClassId,classTypeId,feeCourseNum,periodsNum,name);
        }

        return renewClassRecordList;
    }

    public RenewHistoryData getHistoryData(Integer yearPart, Integer quarterNum, String endDate, Quarter quarterNow){

        RenewHistoryData renewHistoryData = new RenewHistoryData();
        LocalDate endDateFormat = LocalDate.parse(endDate);
        LocalDate dateNow = LocalDate.now();
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = 0;
        if (!quarterNow.getYearPart().equals(yearPart) || !quarterNow.getNum().equals(quarterNum)){
            isHistory = 1;
        }
        Integer targetType = 0;//0校长指标，1老师指标
        boolean dateHistory = false;//按天看的历史数据
        Quarter searchQuarter = iQuarterService.getOneForYearAndNum(yearPart,quarterNum);
        //当前学期
        if (isHistory.equals(0)){
            if (dateNow.equals(endDateFormat)){
                dateHistory = false;
            }else {
                dateHistory = true;
            }
        }else {
            //非当前学期
            if (searchQuarter != null && searchQuarter.getEndDate().equals(endDateFormat)){
                //等于学期最后一天，校长指标
                targetType = 0;
            }else if (searchQuarter != null && endDateFormat.isBefore(searchQuarter.getEndDate())){
                //小于学期最后一天，按天看历史数据
                dateHistory = true;
            }else {
                //大于学期最后一天，老师指标
                targetType = 1;
            }
        }
        renewHistoryData.setIsHistory(isHistory);
        renewHistoryData.setDateHistory(dateHistory);
        renewHistoryData.setTargetType(targetType);
        return  renewHistoryData;
    }

    @Override
    public List<RenewClassRecord> staffAnalysis(String schoolId,String yearPart, String quarterNum, String subjectsId,String teacherStr) {
        Quarter quarterNow = iQuarterService.getNowQuarter();

        //是否查看历史的，1是，0否
        Integer isHistory = 0;
        if (!String.valueOf(quarterNow.getYearPart()).equals(yearPart) || !String.valueOf(quarterNow.getNum()).equals(quarterNum)){
            isHistory = 1;
        }
        System.err.println("年份"+yearPart+"季度"+quarterNum);

        List<RenewClassRecord> renewClassRecordList = orderDetailMapper.staffAnalysis(schoolId,yearPart,quarterNum,subjectsId,isHistory,teacherStr);

        return renewClassRecordList;
    }

    /**
     * 续报率
     * @param subjectsId
     * @param type
     * @param quarterNum
     * @param startDate
     * @param endDate
     * @param trackId
     * @return
     * @throws ParseException
     */
    @Override
    public List<ContinueInfo> getContinueFee(Integer yearPart, Integer quarterNum, String schoolId, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer lessonType,String yearClassId,String classTypeId,String name) throws ParseException {

        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart,quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        List<ContinueInfo> continueInfoList = teacherContinueInfoMapper.getRenewRecord(schoolId,yearPart,quarterNum,nextYearPart,nextQuarterNum,subjectsId,type,startDate,endDate,lessonType,trackId,yearClassId,classTypeId,name);
        for (ContinueInfo continueInfo :continueInfoList){
            if (continueInfo.getStudentAllCount()>0){
                BigDecimal continueRate = new BigDecimal(continueInfo.getSchedulingCount()).divide(new BigDecimal(continueInfo.getStudentAllCount()),4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                continueInfo.setContinueRate(continueRate);
            }else {
                continueInfo.setContinueRate(new BigDecimal(0));
            }
        }
        return  continueInfoList;
    }

}
